package com.codingke.codingbookstore.ui;

import android.content.Intent;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.TextView;

import com.astuetz.PagerSlidingTabStrip;
import com.codingke.codingbookstore.App;
import com.codingke.codingbookstore.R;
import com.codingke.codingbookstore.ui.fragment.BookAuthorDescriptionFragment;
import com.codingke.codingbookstore.ui.fragment.BookCatalogFragment;
import com.codingke.codingbookstore.ui.fragment.BookContentDescriptionFragment;
import com.codingke.codingbookstore.ui.fragment.BookPublishingFragment;
import com.codingke.codingbookstore.utils.AppUtils;
import com.codingke.codingbookstore.utils.Constant;
import com.codingke.codingbookstore.utils.NumberUtils;
import com.codingke.codingbookstore.vo.BookInfo;
import com.codingke.codingbookstore.vo.Comment;
import com.codingke.codingbookstore.vo.Orders;
import com.codingke.codingbookstore.vo.User;
import com.lidroid.xutils.bitmap.BitmapDisplayConfig;
import com.lidroid.xutils.bitmap.core.BitmapSize;

import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.listener.CountListener;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;

public class BookDetailActivity extends BaseActivity implements View.OnClickListener {

    private PagerSlidingTabStrip tabs;
    private ViewPager pager;
    private TextView textView4_discountPrice, textView5_price, textView6_discount, textView7_bookName,
            textView8_author;
    private ImageView imageView_book_detail;
    private ArrayList<Fragment> fragments = new ArrayList<>();
    private BookInfo bookInfo;
    private Button button_Shopping_Cart;
    private ImageView imageView_shopping_cart;

    //评价相关的组件
    private LinearLayout linearLayout4_comment;
    private TextView textView10_comment_count;
    private ImageView imageView_userIcon;
    private TextView textView11_username;
    private TextView textView12_createdAt;
    private RatingBar ratingBar_star;
    private TextView textView13_comment_content;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_book_detail);
        bookInfo = (BookInfo) getIntent().getSerializableExtra("bookInfo");
        tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);
        pager = (ViewPager) findViewById(R.id.pager);
        initFragment();
        pager.setAdapter(new MyFragmentAdapter(getSupportFragmentManager()));
        pager.addOnPageChangeListener(null);

//        final int pageMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, getResources()
//                .getDisplayMetrics());
//        pager.setPageMargin(pageMargin);
        tabs.setViewPager(pager);
//
//        tabs.setIndicatorColor(0xfff6f6f6);//指示器
        tabs.setTextColor(0xFF3E3E39);//文本
//        tabs.setBackgroundColor(0xff489cfa);//背景
        tabs.setTypeface(Typeface.DEFAULT, 0);//字体类型


        pager.setCurrentItem(0);

        initView();


    }

    private void initView() {
        textView4_discountPrice = (TextView) findViewById(R.id.textView4_discountPrice);
        textView5_price = (TextView) findViewById(R.id.textView5_price);
        textView6_discount = (TextView) findViewById(R.id.textView6_discount);
        textView7_bookName = (TextView) findViewById(R.id.textView7_bookName);
        textView8_author = (TextView) findViewById(R.id.textView8_author);
        imageView_book_detail = (ImageView) findViewById(R.id.imageView_book_detail);
        button_Shopping_Cart = (Button) findViewById(R.id.button_Shopping_Cart);
        imageView_shopping_cart = (ImageView) findViewById(R.id.imageView_shopping_cart);
        button_Shopping_Cart.setOnClickListener(this);
        imageView_shopping_cart.setOnClickListener(this);

        //评论相关组件
        linearLayout4_comment = (LinearLayout) findViewById(R.id.linearLayout4_comment);
        linearLayout4_comment.setOnClickListener(this);
        textView10_comment_count = (TextView) findViewById(R.id.textView10_comment_count);
        imageView_userIcon = (ImageView) findViewById(R.id.imageView_userIcon);
        textView11_username = (TextView) findViewById(R.id.textView11_username);
        textView12_createdAt = (TextView) findViewById(R.id.textView12_createdAt);
        ratingBar_star = (RatingBar) findViewById(R.id.ratingBar_star);
        textView13_comment_content = (TextView) findViewById(R.id.textView13_comment_content);


        //init data
        initBook();
        initComment();
    }

    private void initBook() {
        textView4_discountPrice.setText("￥" + NumberUtils.format(bookInfo.getDiscountPrice()));
        textView5_price.setText("￥" + NumberUtils.format(bookInfo.getPrice()));
        textView5_price.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
        textView6_discount.setText(NumberUtils.format(bookInfo.getDiscount()) + "折");
        textView7_bookName.setText(bookInfo.getBookName());
        textView8_author.setText(bookInfo.getAuthor());
        BitmapDisplayConfig config = new BitmapDisplayConfig();
        config.setBitmapMaxSize(new BitmapSize(App.screenWidth, 240));
        App.bitmapUtils.display(imageView_book_detail, Constant.BMOBFILE_ROOT + bookInfo.getBookImage().getUrl(), config);
    }


    private int commentCount = 0; //评价的总数
    private Comment comment; //最新的一条评价

    private void initComment() {
        final BmobQuery<Comment> query = new BmobQuery<>();
        query.addWhereEqualTo("bookInfoId", bookInfo.getObjectId());
        query.order("-createdAt");
        query.count(this, Comment.class, new CountListener() {
            @Override
            public void onSuccess(int i) {
                commentCount = i;
                if (commentCount > 0) {
                    query.setLimit(1);
                    query.findObjects(BookDetailActivity.this, new FindListener<Comment>() {
                        @Override
                        public void onSuccess(List<Comment> list) {
                            comment = list.get(0);
                            updateCommentUI();
                        }

                        @Override
                        public void onError(int i, String s) {

                        }
                    });
                }
            }

            @Override
            public void onFailure(int i, String s) {

            }
        });


    }

    private void updateCommentUI() {
        textView10_comment_count.setText("(共有"+commentCount+"条评论)");
        if(comment!=null){
            textView11_username.setText(AppUtils.formatPhoneNumber(comment.getUser()));
            textView12_createdAt.setText(comment.getCreatedAt());
            ratingBar_star.setRating(comment.getStar());
            textView13_comment_content.setText(comment.getContent());
        }

    }


//    public void backClick(View view){
//        finish();
//    }

    //
    private void initFragment() {
        //BookContentDescriptionFragment,BookAuthorDescriptionFragment,BookCatalogFragment
        //三个都是HTML的内容
        fragments.add(BookContentDescriptionFragment.newInstance(bookInfo.getContentDescription()));
        fragments.add(BookAuthorDescriptionFragment.newInstance(bookInfo.getAuthorDescription()));
        fragments.add(BookCatalogFragment.newInstance(bookInfo.getCatalog()));

        fragments.add(BookPublishingFragment.newInstance(bookInfo));
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //加入购物车功能
            case R.id.button_Shopping_Cart:
                addShoppingCart();
                break;
            //查看我的购物车
            case R.id.imageView_shopping_cart:
                viewShoppingCart();
                break;
            case R.id.linearLayout4_comment:
                if(commentCount>0){
                    Intent intent = new Intent(this,CommentActivity.class);
                    intent.putExtra("bookInfoId",bookInfo.getObjectId());
                    startActivity(intent);
                }else{
                    showToast("没有更多评论了");
                }
                break;
        }
    }

    //查看购物车
    private void viewShoppingCart() {
        //判断用户是否已经登录
        User user = BmobUser.getCurrentUser(this, User.class);
        if (user == null) {
            showToast("请登录后再查看购物车");
            startActivity(new Intent(this, LoginActivity.class));
            return;
        }
        startActivity(new Intent(this, ShoppingCartActivity.class));
    }


    //加入购物车
    private void addShoppingCart() {

        //判断用户是否已经登录
        final User user = BmobUser.getCurrentUser(this, User.class);
        if (user == null) {
            showToast("请登录后再购买");
            startActivity(new Intent(this, LoginActivity.class));
            return;
        }

        // 查询购物车中是否存在该商品
        BmobQuery<Orders> query = new BmobQuery<>();
        query.addWhereEqualTo("userId", user.getObjectId());
        query.addWhereEqualTo("bookInfoId", bookInfo.getObjectId());
        query.addWhereEqualTo("status", Constant.ORDER_NON_PAYMENT);
        query.findObjects(this, new FindListener<Orders>() {
            @Override
            public void onSuccess(List<Orders> list) {
                List<Orders> ordersList = list;
                //更新订单
                if (ordersList.size() > 0) {
                    Orders orders = ordersList.get(0);
                    orders.setTotal(orders.getTotal() + 1);
                    orders.setSubtotal(orders.getTotal() * orders.getDiscountPrice());
                    orders.update(BookDetailActivity.this, new UpdateListener() {
                        @Override
                        public void onSuccess() {
                            showToast("加入购物车成功");
                        }

                        @Override
                        public void onFailure(int i, String s) {
                            showToast("加入购物车失败");
                        }
                    });
                } else {
                    //保存订单
                    Orders o = new Orders();
                    o.setUserId(user.getObjectId());//用户ID
                    o.setBookInfoId(bookInfo.getObjectId());//图书ID
                    o.setTotal(1);//设置购买数量为1
                    o.setStatus(Constant.ORDER_NON_PAYMENT);//设置图书状态(未付款)
                    o.setBookName(bookInfo.getBookName());//书名
                    o.setDiscountPrice(bookInfo.getDiscountPrice());//书单价
                    o.setSubtotal(o.getTotal() * o.getDiscountPrice());//订单小计金额
                    o.setBookImage(bookInfo.getBookImage().getUrl());//图书图片路径
                    //保存
                    o.save(BookDetailActivity.this, new SaveListener() {
                        @Override
                        public void onSuccess() {
                            showToast("加入购物车成功");
                        }

                        @Override
                        public void onFailure(int i, String s) {
                            showToast("加入购物车失败");
                        }
                    });
                }
            }

            @Override
            public void onError(int i, String s) {
                Log.e(getClass().getName(), s);
            }
        });
    }

    class MyFragmentAdapter extends FragmentPagerAdapter {
        private String[] titles = {"内容", "作者", "目录", "出版"};

        public MyFragmentAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return titles[position];
        }

        @Override
        public Fragment getItem(int position) {
            return fragments.get(position);
        }

        @Override
        public int getCount() {
            return titles.length;
        }
    }
}
